package de.ohmhochschule.bme;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.StringTokenizer;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Creates a WebView and loads it with a local webpage.  Notice, that it
 * also loads stylesheets and images from the local storage (/res/raw/).
 */
public class DetailActivity extends Activity {
	public static final String STARTING_PAGE = "de.ohmhochschule.bme.which_page";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		int pageNr = getIntent().getIntExtra(STARTING_PAGE, 0);
		
		//this.setTitle("Page: "+pageNr);
		this.setTitle("Kathy");
		WebView webView = new WebView(this);
		webView.setWebViewClient( new DetailWebViewClient() );
		String html = readFile( pageNr );
		webView.loadDataWithBaseURL("file:///android_res/raw/", html, 
		                            "text/html", "UTF-8", null);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.getSettings().setSupportZoom(true);
		setContentView(webView);
	}

	/**
	 * This reads a file from the /res/raw/ folder, for instance /res/raw/index0.html
	 * Uses a little reflection, otherwise straight forward. 
	 * @param pageNr gives the number in index0.html
	 * @return a web page as HTML
	 */
	private String readFile(int pageNr) {
		Field f = null;
		try {
			f = R.raw.class.getField("index"+pageNr);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		StringBuffer sb = new StringBuffer();
		try {
			InputStream htmlStream = getResources().openRawResource(f.getInt(null));
			BufferedReader is = new BufferedReader(new InputStreamReader(htmlStream, "UTF8"));
			String line;
			while ((line = is.readLine()) != null) {
				sb.append(line);
			}
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return sb.toString();
	}


	/**
	 * This makes sure that you are not opening an external browser when clicking on links.
	 * Depending on the link types, we perform different actions. 
	 * @see android-sdk/docs/resources/tutorials/views/hello-webview.html
	 */
	private class DetailWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.i("test-","url: "+url);
			if ( url.startsWith("tel:") ) {
				startPhoneActivity();	
			} else if ( url.startsWith("cal:") ) {
				startCalendarActivity(url);
			} else if ( url.startsWith("ext:") ) {
				startExternalBrowser(url);
			} else {
				view.loadUrl(url);				
			}
			return true;
		}

		private void startExternalBrowser(String url) {
			//Uri uri = Uri.parse("http://www.openstreetmaps.org/?lat=49.452&lon=11.082&zoom=20");
			//Uri uri = Uri.parse("http://maps.google.com/?q=Am%20Katharinenkloster%206,90403%20Nuremberg,Germany");
			Uri uri = Uri.parse(url.substring(4));
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
		}

		/**
		 * 
		 * @param startDateTimeURL is of the form cal:2012_06_16_20_00_EventName_Description_Location
		 */
		private void startCalendarActivity(String startDateTimeURL) {
			StringTokenizer st = new StringTokenizer(startDateTimeURL.substring(4),"_");
			int year = Integer.parseInt( st.nextToken() );
			int month = Integer.parseInt( st.nextToken() );
			int day = Integer.parseInt( st.nextToken() );
			int hour = Integer.parseInt( st.nextToken() );
			int minute = Integer.parseInt( st.nextToken() );
			String sEventTitle = st.nextToken();
			String sDescription = st.nextToken();
			String sLocation = st.nextToken();

			// http://stackoverflow.com/questions/4373074/how-to-launch-android-calendar-application-using-intent-froyo
			long startMillis = 0;
			long endMillis = 0;
			Calendar beginTime = Calendar.getInstance();
			beginTime.set(year, month, day, hour, minute);
			startMillis = beginTime.getTimeInMillis();
			Calendar endTime = Calendar.getInstance();
			endTime.set(year, month, day, hour+1, minute);
			endMillis = endTime.getTimeInMillis();

			Intent intent = new Intent(Intent.ACTION_EDIT);  
			intent.setType("vnd.android.cursor.item/event");
			intent.putExtra("title", sEventTitle);
			intent.putExtra("eventLocation", sLocation);
			intent.putExtra("description", sDescription);
			intent.putExtra("beginTime", startMillis);
			intent.putExtra("endTime", endMillis);
			startActivity(intent);
		}

		private void startPhoneActivity() {
			Uri uri = Uri.parse("tel:+49 911 213 2050");
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
		}
		
	}
}
